import {formatDate,formatExcelDate} from '../date'



// 导出Excel
export function exportExcel(cols, datas, name = defaultName(), save) {
  if (save === undefined) save = true
  return new Promise((resolve, reject) => {
    if (!(cols && datas)) reject()
    require.ensure([], () => {
      const { export_json_to_excel } = require('./Export2Excel')
      /* 设置Excel的表格第一行的标题 */
      const tHeader = cols.map(v => v.title)
      /* 把data里的list存到list */
      const dataList = formatJson(cols, datas)
      /* 最后一个项为导出的excel名字 */
      resolve(export_json_to_excel(tHeader, dataList, name, save))
    })
  })
}

// 格式化数据
function formatJson(cols, list) {
  const dataList = []
  for (let i = 0, len = list.length; i < len; i++) {
    const item = list[i]
    const temp = []
    for (const { key, render } of cols) {
      if (typeof render === 'function') {
        temp.push(render(item, i))
      } else {
        temp.push(item[key])
      }
    }
    dataList.push(temp)
  }
  return dataList
}

function defaultName() {
  const d = new Date(),
    y = d.getFullYear(),
    m = d.getMonth() + 1,
    day = d.getDay()
  return `TABLE-${y}${m}${day}-${Math.random().toString().slice(2)}`
}

// 导入并解析Excel
export function importExcel(fileObj) {
  return new Promise((resolve, reject) => {
    if (
      fileObj.type != 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' &&
      fileObj.type != 'application/vnd.ms-excel' &&
      fileObj.type != 'application/wps-office.xlsx' &&
      fileObj.type != 'application/vnd.ms-works'
    ) {
      console.log(`Error: 不支持的文件格式(${fileObj.type})`)
      return reject({ code: 0, msg: '附件格式错误' })
    }

    var rABS = false //是否将文件读取为二进制字符串
    var f = fileObj
    var reader = new FileReader()
    //if (!FileReader.prototype.readAsBinaryString) {
    FileReader.prototype.readAsBinaryString = function (f) {
      try {
        var binary = ''
        var rABS = false //是否将文件读取为二进制字符串
        var wb //读取完成的数据
        var outdata
        var reader = new FileReader()
        reader.onload = function (e) {
          var bytes = new Uint8Array(reader.result)
          var length = bytes.byteLength
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i])
          }
          var XLSX = require('xlsx')
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: 'base64'
            })
          } else {
            wb = XLSX.read(binary, {
              type: 'binary'
            })
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
          const result = [...outdata]
          resolve(result)
        }
        reader.readAsArrayBuffer(f)
      } catch (error) {
        reject({ code: 1, msg: error })
      }
    }

    if (rABS) {
      reader.readAsArrayBuffer(f)
    } else {
      reader.readAsBinaryString(f)
    }
  })
}

// 验证并替换key为对应的字段
export function repleceKeys(keys, list) {
  let index = 1,
    err = 0,
    valiNGList = []
  const result = list.reduce((temp, item) => {
    const res = {}
    for (const [ckey, { key, required, validator }] of Object.entries(keys)) {
      // const { key, required, validator } = keys[ckey] || {};
      res[key] = item[ckey]
      if(/(日期)|(时间)|(年月)/.test(ckey) && item[ckey]) {
        try {
          if(typeof item[ckey] == 'number') {
            res[key] = formatDate(formatExcelDate(item[ckey]), 'YYYY-MM-DD HH:mm:ss')
          } else {
            res[key] = formatDate(item[ckey], 'YYYY-MM-DD HH:mm:ss')
          }
        } catch (error) {}
      }
      // 自定义验证
      if (typeof validator == 'function') {
        validator(item[ckey], item, error => {
          if (typeof error === 'object') {
            err = 1
            valiNGList.push([ckey, index, error.message])
          }
        })
      } else if (required) {
        // 为空验证
        if (item[ckey] === null || item[ckey] === undefined || item[ckey] === '') {
          err = 1
          valiNGList.push([ckey, index])
        }
      }
    }

    index++
    return [...temp, res]
  }, [])
  // 验证不通过
  if (err === 1) return [1, valiNGList]
  // 验证通过
  return [0, result]
}
